<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :close-on-click-modal="false" width="500px">
			<el-alert :closable="false" title="步骤一 导出发货单" type="warning" class="mb5" />
			<el-alert :closable="false" title="步骤二 发货单中填写物流单号" type="warning" class="mb5" />
			<el-alert :closable="false" title="步骤三 将发货单上传" type="warning" class="mb5" />
			<el-form :model="state.ruleForm" label-width="auto">
				<el-form-item prop="files">
					<FileUpload ref="fileUploadRef" @fileUpload="onFileUpload" :action="state.actionUrl" :fileList="state.ruleForm.files" :autoUpload="false" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="state.dialog.submitLoading" size="default">提 交</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { nextTick, reactive, ref } from 'vue';

import { orderApi } from '/@/api';

let callback: Function = () => {};
const OrderApi = orderApi();
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '批量发货',
		submitLoading: false,
	},
	ruleForm: {
		files: [] as any,
	},
	actionUrl: OrderApi.orderImport(),
});
const fileUploadRef = ref();

/********** 触发事件 **********/
// 回调文件上传
const onFileUpload = (res: any, file: any) => {
	state.ruleForm.files.push(file);
	if (res.msg !== 'ok') {
		state.ruleForm = {
			files: [],
		};
		fileUploadRef.value.initialize();
		ElMessage.error(res.msg);
	} else {
		ElMessage.success('操作成功！请耐心等待任务执行');
		state.dialog.isShowDialog = false;
		onCancel();
		callback();
	}
};

// 取消
const onCancel = () => {
	state.dialog = {
		isShowDialog: false,
		type: '',
		title: '批量发货',
		submitLoading: false,
	};
};
// 提交
const onSubmit = () => {
	state.dialog.isShowDialog = true;
	fileUploadRef.value.submit();
};

/********** 方法事件 **********/
// 打开
const openDialog = (fn: Function) => {
	state.dialog.isShowDialog = true;
	callback = fn;
	state.ruleForm = {
		files: [],
	};
	nextTick(() => {
		fileUploadRef.value.initialize();
	});
};

/********** 方法向父组件暴露 **********/
defineExpose({ openDialog });
</script>
